// Copyright 2019 The rhyme_lph Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
// j [author] rhyme_lph
// Q [email]  rhymelph@gmail.com
// I [github] https://github.com/rhymelph

import 'dart:io';

import 'package:base_plugin/base_plugin.dart';
import 'package:finance_app/generated/l10n.dart';
import 'package:finance_app/src/router_gen/router_gen_providers.dart';
import 'package:finance_app/src/widgets/bottom_sheet/photo_preview_bottom_sheet.dart';
import 'package:flutter/material.dart';
import 'package:photo_manager/photo_manager.dart';
import 'package:pull_to_refresh/pull_to_refresh.dart';

class SelectPhotoProvider extends BaseProvider {
  String currentTab = 'Photos';
  bool isShowError = false;

  List<AssetEntity> assetList = [];
  AssetPathEntity currentSelectPath;

  bool isSelect = false;

  RefreshController refreshController = RefreshController();

  int page = 0;
  int pageSize = 20;

  @override
  Future get dataFuture => null;

  @override
  void initState() {
    super.initState();
    _onRequestPermission();
  }

  @override
  void dispose() {
    super.dispose();
    PhotoManager.clearFileCache();
    refreshController.dispose();
  }

  void onChangeTab(Object value) {
    if (currentTab != value) {
      currentTab = value;
      update();
    }
  }

  void _onRequestPermission() async {
    final result = await PhotoManager.requestPermission();
    if (result == true) {
      final assetGroup = await PhotoManager.getAssetPathList(
        onlyAll: true,
        type: RequestType.image,
      );
      currentSelectPath = assetGroup[0];
      assetList = await currentSelectPath.getAssetListPaged(page, pageSize);
      // assetList = await assetGroup[0].assetList;
      update();
    } else {
      isShowError = true;
      update();
    }
  }

  void onSelectImage(File data) {
    obtainContext?.call((context) async {
      if (isSelect == true) {
        Navigator.of(context).pop(data.path);
      } else {
        bool isSuccess = await showPhotoPreviewBottomSheet(context, data, null,
            onSelect: () => Navigator.of(context).pop(true),
            chooseAgainText: S.current.choose_again,
            onChooseAgain: () => Navigator.of(context).pop(false));
        if (isSuccess == true) {
          await Routes.navigateTo(RouterGenProviders.reviewPhotoPage,
              params: {
                'filepath': data.path,
                'isFromPhoto': true,
              },
              replace: true);
        }
      }
    });
  }

  void onLoadMore() async {
    //加载更多
    page++;
    final result = await currentSelectPath.getAssetListPaged(page, pageSize);
    assetList.addAll(result);
    refreshController.loadComplete();
    update();
  }
}
